package org.example.framework.register;


import java.io.*;
import java.net.URL;
import java.util.*;

public class RemoteMapRegister {
    private static volatile Map<String, Map<String, List<URL>>> REGISTER = new HashMap<>();

    public static void register(String interfaceName, URL url) {
        Map<String, List<URL>> listMap = REGISTER.get(interfaceName);
        List<URL> list = null;
        if (listMap == null) {
            listMap = new HashMap<>();
            list = new ArrayList<>();
        } else {
            list = listMap.get("");
        }
        list.add(url);
        listMap.put("", list);

        REGISTER.put(interfaceName, listMap);
        saveFile();
    }

    public static void register(String interfaceName, URL url, Set<String> tags) {
        Map<String, List<URL>> listMap = REGISTER.get(interfaceName);

        if (tags == null || tags.isEmpty()) {
            tags = new HashSet<>();
            tags.add("");
        }
        if (listMap == null) {
            listMap = new HashMap<>();
        }
        for (String tag : tags) {
            List<URL> list = new ArrayList<>();
            List<URL> urlList = listMap.get(tag);
            if (urlList == null) {
                urlList = new ArrayList<>();
            }
            list.addAll(urlList);
            list.add(url);
            listMap.put(tag, list);
        }

        REGISTER.put(interfaceName, listMap);
        saveFile();
    }


    public static Map<String, List<URL>> get(String interfaceName) {
        REGISTER = getFile();
        return REGISTER.get(interfaceName);
    }


    private static void saveFile() {
        try {
            FileOutputStream fileoutputStream = new FileOutputStream("/temp.txt");
            ObjectOutputStream objectoutputStream = new ObjectOutputStream(fileoutputStream);
            objectoutputStream.writeObject(REGISTER);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, Map<String,List<URL>>> getFile() {
        try {
            FileInputStream fileInputStream = new FileInputStream("/temp.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            return (Map<String, Map<String,List<URL>>>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
